import type { App } from 'vue'
import { useUserStoreWithOut } from '@/stores/modules/user'

const { t } = useI18n()

export const setupHasPermi = (app: App<Element>) => {
  app.directive('hasPermi', (el, binding) => {
    const { value } = binding
    const all_permission = '*:*:*'
    const permissions = useUserStoreWithOut().permissions

    if (value && value instanceof Array && value.length > 0) {
      const permissionFlag = value

      const hasPermission = permissions.some((permission: string) => {
        return all_permission === permission || permissionFlag.includes(permission)
      })

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(t('permission.hasPermission'))
    }
  })
}
